import { ipcMain, dialog } from 'electron'

// eslint-disable-next-line @typescript-eslint/no-var-requires
// const fs = require('fs');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const spawn = require('cross-spawn')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const child_process = require('child_process')

// eslint-disable-next-line @typescript-eslint/no-var-requires
const os = require('os')

import { MERGE_CONFIG_TOOL_PATH, fileType, appPath, asarPath } from './const'

export function initIpc() {
  console.log('init ipc')
  let lastChildProcess

  let cmd = 'ffmpeg'
  const env = {
    ...process.env,
    PATH: '/usr/local/bin:' + child_process.execSync('echo $PATH').toString()
  }

  if (os.platform() == 'win32') {
    cmd = MERGE_CONFIG_TOOL_PATH
  }

  // 选择文件
  ipcMain.handle('selectDic', async () => {
    const { filePaths } = await dialog.showOpenDialog({
      title: '请选择要导入的视频',
      // properties: ['openFile', 'multiSelections'],
      properties: ['openDirectory']
    })
    return filePaths[0] ? filePaths[0] + '\\' : ''
  })
  // fileType 指定文件类型
  ipcMain.handle('selectVideoFiles', async () => {
    console.log('filetype', fileType)
    const { filePaths } = await dialog.showOpenDialog({
      title: '请选择导出视频位置',
      filters: [{ name: '视频格式', extensions: [] }],
      // filters: [{ name: '视频格式', extensions: fileType }], // 指定视频格式
      properties: ['openFile', 'multiSelections']
    })
    return filePaths || []
  })
  // 合并文件
  ipcMain.handle('merge-merges', async (event, arg) => {
    console.log('arg', event, arg)
    return await new Promise((resolve) => {
      if (lastChildProcess) {
        lastChildProcess.kill()
        lastChildProcess = null
      }

      // 判断文件是否存在
      // return fs.existsSync(arg.output:)
      // // eslint-disable-next-line @typescript-eslint/no-unused-vars
      // function hasFile(path: string) {
      //   return fs.existsSync(path)
      // }

      let cmdStr = ['-y', '-i', `concat:${arg.input}`, '-c', 'copy', arg.output]

      if (arg.type === 'wmv' || arg.type == 'mp3') {
        cmdStr = ['-i', arg.input, arg.output]
      }

      // 创建一个子进程
      lastChildProcess = spawn(cmd, cmdStr, {
        env: env
      })

      //
      lastChildProcess.stdout.on('data', (data) => {
        console.log('stdout:', data)

        // event.reply("merge-merge-result", {
        //     type: "stdout",
        //     data: data.toString(),
        // });
      })
      lastChildProcess.stderr.on('data', () => {
        // console.log('stderr:123',data.toString())
        // event.reply('merge-merge-result', {
        //   type: 'stderr',
        //   data: data.toString()
        // })
      })
      lastChildProcess.on('close', () => {
        resolve({
          success: true,
          message: '转换成功'
        })
      })
      lastChildProcess.on('error', (data) => {
        // resolve(false)
        resolve({
          success: false,
          message: '转换失败',
          path: data.toString()
        })
        // event.reply("merge-merge-result", {
        //     type: "err",
        //     data: data.toString(),
        // });
      })
    })
  })
  ipcMain.on('merge-merge', (event, arg) => {
    if (!lastChildProcess) {
      lastChildProcess.kill()
      lastChildProcess = null
    }

    lastChildProcess = spawn(cmd, ['-y', '-i', `concat:${arg.input}`, '-c', 'copy', arg.output], {
      env: env
    })
    lastChildProcess.stdout.on('data', (data) => {
      event.reply('merge-merge-result', {
        type: 'stdout',
        data: data.toString()
      })
    })
    lastChildProcess.stderr.on('data', (data) => {
      event.reply('merge-merge-result', {
        type: 'stderr',
        data: data.toString()
      })
    })
    lastChildProcess.on('error', (data) => {
      console.log(data.toString())
      event.reply('merge-merge-result', {
        type: 'err',
        data: data.toString()
      })
    })
  })
  ipcMain.on('init', (event) => {
    event.reply('merge-merge-result', {
      type: 'path',
      data: MERGE_CONFIG_TOOL_PATH,
      appPath,
      asarPath
    })
  })
}
